<template>
  <div class="changeInfo">
    <div>
      <template v-if="show==='define'">
        <h3>请确认原手机{{personalInfo.phone}}是否还能使用</h3>
        <p v-if="vList.email==1">如果手机号不能使用，请使用邮箱验证</p>
        <button v-if="vList.phone==1" class="type1" @click="show='phone'">手机还能用</button>
        <button v-if="vList.email==1" class="type2" @click="show='email'">邮箱验证</button>
      </template>

      <template v-if="show!=='define' && step===1">
        <div class="input-item">
          <input type="text" name="code" v-model="code" @input="isGetCode" placeholder="请输入验证码"/>
          <span v-if="!isShowTime" class="es" @click="getVCode">获取验证码</span>
          <span class="time" v-else>{{time}}s</span>
        </div>
        <button class="btn" :class="{'es':code}" @click="next">下一步</button>
      </template>

      <template v-if="type==='phone' && step===2">
        <div class="input-item">
          <input type="number" name="newPhone" v-model="newPhone" placeholder="请输入新手机号"/>
        </div>
        <button class="btn" :class="{'es':newPhone.trim()}" @click="verifyPhone">完成</button>
      </template>

      <template v-if="type==='email' && step===2">
        <div class="input-item">
          <input type="text" name="newEmail" v-model="newEmail" placeholder="请输入新邮箱"/>
        </div>
        <button class="btn" :class="{'es':newEmail.trim()}" @click="verifyEmail">完成</button>
      </template>

      <template v-if="type==='password' && step===2">
        <div class="input-item">
          <input type="password" name="newPwd" v-model="newPwd" @blur="verifyPwd" placeholder="请输入新密码"/>
        </div>
        <div class="input-item">
          <input type="password" name="againPwd" v-model="againPwd" placeholder="请再次输入新密码"/>
        </div>
        <button class="btn" :class="{'es':isSubmitPwd}" :disabled="!isSubmitPwd" @click="verifyTwoPwd">确定</button>
      </template>
    </div>
  </div>
</template>

<script>
  import CONFIG from './../../config'
  import {Toast} from 'mint-ui';
  import {isMobile, isEmail} from "../../util";
  import {mapState} from 'vuex'

  export default {
    name: "ChangeInfo",
    data() {
      return {
        step: 1,
        show: 'define',
        vList: {phone: 1}, //可用验证方式
        captcha1: {},
        isShowTime: false,
        type: 'password',
        code: '',
        time: 120,
        isRequest: false,
        newPhone: '',
        newEmail: '',
        newPwd: '',
        againPwd: ''
      }
    },
    beforeRouteEnter (to, from, next) {
      next(vm => {
        let params = vm.$route.query;
        vm.type = params.type || 'password';
        let title = vm.type === 'password' ? '修改密码' : (vm.type === 'phone' ? '修改手机号' : '修改邮箱');
        vm.$store.dispatch('changeTitleAction', title);
        document.title =title;
      })
    },
    mounted() {
      this.captcha1 = new TencentCaptcha(CONFIG.appId, this.handleVCode);
      //进来先获取验证列表
      this.$api.getSecurity().then((res) => {
        this.vList = res.data;
      })
    },
    computed: {
      ...mapState({
        personalInfo: state => state.user.personalInfo,
      }),
      isSubmitPwd() {
        return this.newPwd.trim() && this.againPwd
      }
    },
    methods: {
      verifyPhone() {
        //验证是否为手机号
        if (!isMobile(this.newPhone)) {
          this.$toast('手机号格式不正确')
        } else {
          this.mySubmit()
        }
      },
      verifyEmail() {
        //验证是否为邮箱
        if (!isEmail(this.newEmail)) {
          this.$toast('邮箱格式不正确')
        } else {
          this.mySubmit()
        }
      },
      verifyPwd() {
        if (this.newPwd.trim().length < 6) {
          this.$toast('密码不小于6位');
        }
      },
      verifyTwoPwd() {
        if (this.againPwd !== this.newPwd) {
          this.$toast('2次密码输入不一致');
        } else {
          this.mySubmit()
        }
      },
      mySubmit() {
        if (this.type === 'phone') {
          this.changeSetting('securityPhone', 'phone', this.newPhone);
        } else if (this.type === 'email') {
          this.changeSetting('securityEmail', 'email', this.newEmail);
        } else if (this.type === 'password') {
          this.changeSetting('securityPassword', 'password', this.newPwd);
        }
      },
      changeSetting(methodName, propName, value) {
        setTimeout(() => {
          let msg = document.querySelectorAll('.msg');
          if (msg.length === 0) {
            if (!this.isRequest) {
              this.isRequest = true;
              this.$api[methodName]({[propName]: value}).then((res) => {
                this.isRequest = false;
                this.$toast('修改成功');
                this.$router.go(-1)
                this.$store.dispatch('getPersonalInfoAction');
                this.$store.dispatch('getUserInfoAction');
              }).catch((err) => {
                this.isRequest = false;
                this.$toast(err.response.data.msg);
                this.step = 1;
                this.show = 'define'
              })
            }
          }
        }, 0)
      },
      isGetCode() {
        if (!this.isShowTime) {
          this.code = '';
          this.$toast('请先获取验证码');
        }
      },
      test() {
        Toast({
          message: '操作成功',
          iconClass: 'iconfont icon-success',
          duration: -1
        });
      },
      getVCode() {
        this.captcha1.show()
      },
      handleVCode(res) {
        if (res.ret === 0) {
          if (this.show === 'phone') {
            this.getCode('getSecurityPhoneCode');
          } else if (this.show === 'email') {
            this.getCode('getSecurityEmailCode');
          }
        }
      },
      getCode(methodName) {
        if (!this.isRequest) {
          this.isRequest = true;
          this.$api[methodName]().then(() => {
            this.isRequest = false;
            this.interval = setInterval(() => {
              this.time -= 1;
              if (this.show === 'email') {
              }
              if (this.time === 0) {
                clearInterval(this.interval);
                this.isShowTime = false;
                this.time = 120;
              }
            }, 1000);
            this.isShowTime = true;
          }).catch((err) => {
            this.isRequest = false;
            this.$toast(err.response.data.msg);
          })
        }
      },
      next() {
        //在这里需要判断用户需要修改的是什么，电话-邮箱-或者-密码
        if (this.isShowTime && this.code) {
          if (this.show === 'phone') {
            this.sendCode('securityPhoneCode')
          } else if (this.show === 'email') {
            this.sendCode('postSecurityEmailCode')
          }
        }
      },
      sendCode(methodName) {
        if (!this.isRequest) {
          this.isRequest = true;
          this.$api[methodName]({code: this.code}).then((res) => {
            //手机验证成功
            this.step = 2;
            this.isRequest = false;
          }).catch((err) => {
            this.isRequest = false;
            this.$toast(err.response.data.msg);
          })
        }
      },
    }
  }
</script>

<style lang="scss" scoped>
  .changeInfo {
    width: 100%;
    height: 100%;
    background: #fff;
    >div{
      padding: 0.1px 30px;
      .btn {
        background: #ddd;
        margin: 80px 0 0 0;
        &.es {
          background: #E71F18;
        }
      }

      h3 {
        font-size: 34px;
        font-weight: 400;
        color: rgba(51, 51, 51, 1);
        line-height: 34px;
        margin: 64px 0 27px 0;
      }

      > p {
        font-size: 24px;
        font-weight: 400;
        color: rgba(153, 153, 153, 1);
        line-height: 24px;
        margin: 0 0 59px 0;
      }

      .type1 {
        width: 690px;
        height: 88px;
        background: rgba(231, 31, 24, 1);
        border-radius: 6px;
        display: block;
        margin: 0 auto 30px auto;
        font-size: 36px;
        font-weight: 400;
        color: rgba(255, 255, 255, 1);
      }

      .type2 {
        width: 690px;
        height: 88px;
        border-radius: 6px;
        display: block;
        margin: 0 auto 30px auto;
        font-size: 36px;
        font-weight: 400;
        color: #E71F18;
        background: #fff;
        border: 1px solid rgba(231, 31, 24, 1);
      }

      .input-item {
        height: 100px;
        border-bottom: 1px solid #ccc;
        display: flex;
        align-items: center;
        justify-content: space-between;

        &:first-of-type {
          margin: 92px 0 0 0;
        }

        input {
          font-size: 30px;
          line-height: 30px;
          color: #999999;
          text-align: left;
        }

        > span {
          font-size: 30px;
          line-height: 30px;
          color: #999999;

          &.es {
            color: #E71F18;
          }

          &.time {
            margin: 0 30px 0 0;
          }
        }
      }
    }

  }
</style>
